//
//  editMyResumeAddJobExperienceTableViewController.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/5/4.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import WSProgressHUD

enum editMyResumeAddAndEditJobType:String{
    case Add = "add"
    case Edit = "edit"
}

class editMyResumeAddEditJobExperience: UITableViewController {
    
    var workModel:LDMyResumeWorkexperienceModel?
    
    let titleArr = ["职位类别","职位名称","公司名称","公司行业","工作重点","时间段","所属部门","工作内容"]
    var tableview:LDBaseTableView?
    
    var enterButton:UIButton?
    var deleButton:UIButton?
    var timePicker:LDBaseTimePicker?
    
    var bottomView:UIView?
    //传入参数
    var type:editMyResumeAddAndEditJobType = .Add;
//    var jobExpDict = NSDictionary()
    
    var cellContentdict = [Int:String]()
    
    //二级职位类别
    var leve2_id:String?
    var leve2_name:String?
    //
    var editJobInfoDict = [NSDictionary]()
    //
    // 工作重点标签数组
    var jobstrenthsTitleArr = [NSDictionary]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setDefaultContent()
        NSNotificationCenter.defaultCenter()
            .addObserver(self, selector: #selector(getJobCateary(_:)), name: LDBaseTagsView().tagViewNotiName, object: nil)
        NSNotificationCenter.defaultCenter()
            .addObserver(self, selector: #selector(get2JobTitle_ID(_:)), name: sendChose2TitleIDAndTitle, object: nil)
        
    }
    
    func setupDefaultData() {
        
    }
    
    func setDefaultContent() {
        title = "添加工作经历"
        tableview = LDBaseTableView.init(frame: view.bounds, style: UITableViewStyle.Plain)
        tableView = tableview
        
      
        if type == .Edit {
            //021 为 index to id
            
            leve2_id = workModel?.cetegorylevel2id
            leve2_name = workModel?.cetegorylevel2name
            cellContentdict[021] = leve2_id
            cellContentdict[0] = workModel?.cetegorylevel3name
            cellContentdict[1] = workModel?.jobtitle
            cellContentdict[2] = workModel?.companyname
            cellContentdict[3] = workModel?.industryname
            
            let count = workModel?.jobstrenthscount ?? 0
            cellContentdict[4] = String(format: "%d个重点",count)
            
            let start = workModel?.startdate
            let end = workModel?.enddate
        
            cellContentdict[5] = start! + "-" + end!
            cellContentdict[6] = workModel?.department
            cellContentdict[7] = workModel?.jobdesc
        }
        
        setBottomBtn()
    }
    
//MARK: - 回调处理
    //获取职位类别
    func getJobCateary(noti:NSNotification) {
        
        navigationController?.popViewControllerAnimated(false)
        navigationController?.popViewControllerAnimated(false)
        
        cellContentdict[0] = noti.userInfo!["tag"] as? String
        cellContentdict[021] = noti.userInfo!["index"] as? String
        self.tableView?.reloadData()
    }
    //获取2级标签id
    func get2JobTitle_ID(noti:NSNotification) {
        leve2_id = noti.userInfo!["level2_id"] as? String
    }
        
    //获取
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //按钮事件
    func enterBtn() {
        var params = [String:AnyObject]()
        
        if cellContentdict[0] == nil || cellContentdict[2] == nil || cellContentdict[3] == nil || cellContentdict[4]  == nil || cellContentdict[5] == nil {
            showLDAlertView("信息未填写完整")
            return
        }
        
        params["category_id"] = cellContentdict[021]
        params["jobtitle"] = cellContentdict[1]
        params["company_name"] = cellContentdict[2]
        params["industry_id"] = cellContentdict[321]
        params["jobstrength_tags"] = cellContentdict[421]
        
        let start = cellContentdict[5]?.componentsSeparatedByString("-").first
        let end = cellContentdict[5]?.componentsSeparatedByString("-").last
        
        params["startdate"] = getUnixDateFormString(start!)
        params["enddate"] = getUnixDateFormString(end!)
        
        params["department"] = cellContentdict[6]
        params["jobdesc"] = cellContentdict[7]

        //增加
        if type == .Add {
            
            LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.create.workexperience, parameters: params, success: { [weak self] (value) in
                
                
                LDUserInfo.sharedInstance.updataJobFinderMyResume(nil, failure: nil)
                LDShowHUB.shareInstance.showSucc(value as! String)
                self?.pop()
                
            }) { (data, error) in
                
                LDShowHUB.shareInstance.showErr(data as! String)
                
            }
        } else if type == .Edit { //编辑
            params["workexperience_id"] = workModel?.workexperienceid
            LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.edit.workexperience, parameters: params, success: { [weak self](value) in
                
                LDUserInfo.sharedInstance.updataJobFinderMyResume(nil, failure: nil)
                LDShowHUB.shareInstance.showSucc(value as! String)
                self?.pop()
                
            }) { (data, error) in
                
                LDShowHUB.shareInstance.showErr(data as! String)
            }
        }
        
    }
    
    func deleBtn() {
        let jobexp_id = workModel?.workexperienceid
        
        LDUserInfoNet.sharedInstance.deleteJobExperience(jobexp_id,success: { [weak self] (value) in
            
            LDShowHUB.shareInstance.showSucc(value as! String)
            LDUserInfo.sharedInstance.updataJobFinderMyResume(nil, failure: nil)
            self?.pop()
            
        }) { (data) in
            LDShowHUB.shareInstance.showErr(data as! String)
        }
        
    }
    
    func setBottomBtn() {
        
        bottomView = UIView.init(frame: CGRectMake(0, 0, LDFrame.ScreenWidth, 100))
        bottomView?.backgroundColor = LDGolbalColor.BgGoundGray
        tableView.tableFooterView = bottomView
        bottomView?.userInteractionEnabled = true
        
        enterButton = UIButton.setDetailsBtn("保存", picName: nil, btnBackColor: LDGolbalColor.Green, titleColor: LDFontColor.White)
        deleButton = UIButton.setDetailsBtn("删除", picName: nil, btnBackColor: LDGolbalColor.Red, titleColor: LDFontColor.White)
        
        bottomView!.addSubview(deleButton!)
        bottomView!.addSubview(enterButton!)
        
        //确定
        enterButton?.bk_whenTapped({ [weak self] in
            self?.enterBtn()
            })
        //删除
        deleButton?.bk_whenTapped({ [weak self] in
            self?.deleBtn()
            })
        
        
        if type == .Add {
            title = "添加工作经历"
            deleButton?.hidden = true
            cellContentdict[0] = ""
            cellContentdict[6] = ""
            cellContentdict[7] = ""
            enterButton?.snp_makeConstraints(closure: { (make) in
                make.top.equalTo(25)
                make.right.equalTo(-10)
                make.left.equalTo(10)
                make.height.equalTo(45)
            })
        }
        
        if type == .Edit {
            title = "编辑工作经历"
            deleButton?.hidden = false
            enterButton?.snp_makeConstraints(closure: { (make) in
                
                make.left.equalTo((bottomView?.snp_centerX)!).offset(5)
                make.top.equalTo(25)
                make.right.equalTo(-10)
                make.height.equalTo(45)
            })
            
            deleButton?.snp_makeConstraints(closure: { (make) in
                
                make.top.height.equalTo(enterButton!)
                make.left.equalTo(10)
                make.right.equalTo((bottomView?.snp_centerX)!).offset(-5)
                
            })
        }
    }
}

extension editMyResumeAddEditJobExperience {
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return titleArr.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCellWithIdentifier("addJobCell") as? baseMySettingCells
        if cell == nil {
            cell = baseMySettingCells.init(style: .Default, reuseIdentifier: "addJobCell")
        }
        cell?.titleLab?.text = titleArr[indexPath.row]
        
        if (indexPath.row == 6 || indexPath.row == 7) && type == .Add {
            cell?.descLab?.text  = "选填"
        }
        
        if cellContentdict.count != 0 {
            cell?.descLab?.text = cellContentdict[indexPath.row]
        }
        return cell!
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 55
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let index = indexPath.row
        
        switch index {
            
        case 0:
            let vc = LDBaseChoseJobKindsVC()
            vc.title = titleArr[0]
            self.navigationController?.pushViewController(vc, animated: true)
            
        case 1,2,6,7:
            
            creatTitleVC(tableView,index: index)
            
        case 3:
            
            let vc = LDBaseCompanyIncKinds()
            vc.title = titleArr[3]
            vc.getTitleFormCell({ [weak self] (index, title) in
                dispatch_async(dispatch_get_main_queue(), {
                    self?.cellContentdict[3] = title
                    self?.cellContentdict[321] = String(format: "%d",index)
                    self?.tableView.reloadData() })
                })
            push(vc)
            
        case 4:
            
            let vc = editMyResumeHightLight()
            vc.limitTags = .Mystrength
            vc.title = leve2_name
            
            if type == .Edit {
                
                var preTitleArr = [String]()
                
                for item in workModel!.jobstrenths {
                    
                    preTitleArr.append(item["tagid"] as! String)
                }
                vc.preSelHightIDParams = preTitleArr
            }
            
            
            if leve2_id == nil {
                
                showLDAlertView("需要设置职位类别")
            } else {
                
                vc.leve2id = leve2_id!
                vc.getParmasFromSelTags({ [weak self] (dict) in
                    self?.cellContentdict[4] = String.init(format: "%d个重点", dict["tagsNum"] as! Int)
                    self?.cellContentdict[421] = dict.jsonString()
                    self?.tableview?.reloadData()
                })
                push(vc)
            }
        case 5:
            let vc = LDBaseTimeSelVC()
            addChildViewController(vc)
            timePicker = vc.timePicker
            timePicker!.showview(self.view)
            vc.sendDateTimeClosure({ [weak self] (data) in

                self?.cellContentdict[5] = data
                self?.tableview?.reloadData()
            })
            
        default:
            break
        }
    }
    
    func push(vc:UIViewController) {
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func pop() {
        navigationController?.popViewControllerAnimated(true)
    }
    
    func creatTitleVC(table:UITableView,index:Int) {
        
        let vc = LDBaseSetTitleVCViewController()
        vc.title = titleArr[index]
        
        if cellContentdict[index] != nil {
            vc.textStr = cellContentdict[index]!
        }
        
        if index == 7 {
            vc.limit = .Medium
        }
        
        vc.getTitleFromColsure { [weak self] (title) in
            
            self?.cellContentdict[index] = title
            self?.navigationController?.popViewControllerAnimated(true)
            self?.tableView.reloadData()
        }
        
        push(vc)
    }
}


extension editMyResumeAddEditJobExperience {
    
    func getYearAndMon() {
        
        let nowDate = NSDate()
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy.MM"
        let dateString = formatter.stringFromDate(nowDate)
        print(dateString)
    }
}